import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/entrance_guard/api.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class SelectRooms extends StatefulWidget {
  final int? lockDeviceId;
  const SelectRooms({super.key, this.lockDeviceId});

  @override
  State<StatefulWidget> createState() => _SelectRoomsState();
}

class _SelectRoomsState extends State<SelectRooms> {
  List _list = [];
  bool _isLoading = false;

  bool _canSave() {
    return _list.any((item) => item["value"] == true);
  }
  
  Future<void> _getUnboundRooms() async {
    if (_isLoading) return;
    
    setState(() {
      _isLoading = true;
    });
    
    try {
      Map resData = await entranceGuardApi.unboundRooms(widget.lockDeviceId!);
      
      List rooms = resData["data"] ?? [];
      rooms = rooms.map((room) => {
        ...room,
        "value": false
      }).toList();
      
      setState(() {
        _list = rooms;
        _isLoading = false;
      });
    } catch (error) {
      setState(() {
        _isLoading = false;
      });
      print(error);
      EasyLoading.showToast("获取未绑定房间列表失败");
    }
  }
  
  Future<void> _saveBindRooms() async {
    if (!_canSave()) {
      EasyLoading.showToast("请选择要关联的房间");
      return;
    }
    
    try {
      List<int> selectedRoomIds = _list
          .where((room) => room["value"] == true)
          .map<int>((room) => room["roomId"])
          .toList();
      
      await entranceGuardApi.bindRooms({
        "faceLockId": widget.lockDeviceId,
        "roomIds": selectedRoomIds
      });
      
      EasyLoading.showToast("关联成功");
      
      if (context.mounted) {
        Navigator.pop(context, true);
      }
    } catch (error) {
      print(error);
      EasyLoading.showToast("关联失败");
    }
  }

  @override
  void initState() {
    super.initState();
    _getUnboundRooms();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
      title: "关联公区房间",
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      showSearch: false,
      showFloatBtn: false,
      children: [
        Container(
          padding: const EdgeInsets.only(top: 60, bottom: 78),
          child: RefreshIndicator(
            onRefresh: _getUnboundRooms,
            child: _list.isEmpty
              ? const Center(
                  child: Padding(
                    padding: EdgeInsets.only(top: 100),
                    child: Text("暂无可关联的房间"),
                  ),
                )
              : ListView.separated(
                  itemBuilder: (context, index) {
                    final room = _list[index];
                    return GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () => setState(() {
                        room["value"] = !room["value"];
                      }),
                      child: Container(
                        padding: const EdgeInsets.all(ThemeVars.paddingPage),
                        decoration: const BoxDecoration(
                          color: Colors.white,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("${room["buildingName"]}${room["name"]}" ?? ""),
                            Icon(
                              room["value"] ? Icons.check_circle : Icons.circle_outlined,
                              color: ThemeVars.colorPrimary,
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context, index) => const SolidDivider(padding: EdgeInsets.only(left: 12)),
                  itemCount: _list.length
              ),
          ),
        ),
        Positioned(
          width: MediaQuery.of(context).size.width,
          top: 0,
          left: 0,
          child: Container(
            width: MediaQuery.of(context).size.width,
            decoration: const BoxDecoration(
              color: ThemeVars.colorBackground,
            ),
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
                  decoration: const BoxDecoration(
                    color: Colors.white
                  ),
                  child: const SizedBox(
                    height: 40,
                    child: TextField(
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(5)),
                          borderSide: BorderSide.none
                        ),
                        hintText: "请输入",
                        isDense: true,
                        filled: true,
                        fillColor: ThemeVars.colorBackground,
                        suffixIcon: SizedBox(
                          child: Icon(Icons.search, size: 20,),
                        ),
                      ),
                      style: TextStyle(fontSize: 14),
                    ),
                  ),
                ),
                const SizedBox(height: 10, child: DecoratedBox(decoration: BoxDecoration(color: ThemeVars.colorBackground)),)
              ],
            )
          )
        ),
        Positioned(
          bottom: 0,
          left: 0,
          width: MediaQuery.of(context).size.width,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 16),
            decoration: const BoxDecoration(
              color: Colors.white,
              boxShadow: [ThemeVars.boxShadow]
            ),
            child: Button(
              type: ButtonType.primary,
              onPressed: _canSave()
                ? _saveBindRooms
                : null,
              child: const Text("保存")
            ),
          )
        ),
      ],
    );
  }
}